package temp.lho.lws.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import temp.lho.lws.emum.MsgStatusEmum;
import temp.lho.lws.result.ResultBody;
import temp.lho.lws.utils.RandomCaptcha;
import temp.lho.lws.vo.LoginVo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登陆controller
 *
 * @author liuws
 * @create 2020-07-02 19:22
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @PostMapping("/login")
    public ResultBody test(@RequestBody LoginVo loginVo, HttpSession session) {

        //获取验证码
        String captcha = (String) session.getAttribute("captcha");

        if (StringUtils.isEmpty(captcha) || !captcha.toLowerCase().equals(loginVo.getCaptcha().toLowerCase())) {
            return ResultBody.toResultBody(MsgStatusEmum.USER_LOGIN_CODE_ERROR_MSG.getCode(),
                    MsgStatusEmum.USER_LOGIN_CODE_ERROR_MSG.getMsg());
        }

        // 获取当前主体
        Subject subject = SecurityUtils.getSubject();
        // 创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUseraccount(), loginVo.getPassword());
        // 认证
        subject.login(token);
        // 如果认证成功
        if (subject.isAuthenticated()) {
        //用户名存入session
            session.setAttribute("user", subject.getPrincipal());
            return ResultBody.toResultBody(MsgStatusEmum.USER_LOGIN_SUCCESS_MSG.getCode(),
                    MsgStatusEmum.USER_LOGIN_SUCCESS_MSG.getMsg());
        } else {
            return ResultBody.toResultBody(MsgStatusEmum.USER_LOGIN_ERROR_MSG.getCode(),
                    MsgStatusEmum.USER_LOGIN_ERROR_MSG.getMsg());
        }
    }

    @GetMapping("/initCaptcha")
    public void initCaptcha(HttpServletRequest request, HttpServletResponse response) {

        response.setContentType("image/jpeg");

        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        RandomCaptcha randomCaptcha = new RandomCaptcha();
        try {
            randomCaptcha.getRandcode(request, response);//输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
